<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            clearable
            v-model="queryInfo.query"
            @clear="ClearSearch"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUser"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <template>
        <el-table :data="UserList" border style="width: 100%;">
          <el-table-column type="index" label="序号"> </el-table-column>
          <el-table-column prop="username" label="用户名" width="80px">
          </el-table-column>
          <el-table-column prop="mobile" label="手机号"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column label="状态" width="100px">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="switchStatus(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope" width="300px">
              <el-tooltip
                class="item"
                effect="dark"
                content="编辑用户"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="clickEditUser(scope.row.id)"
                ></el-button>
              </el-tooltip>

              <el-tooltip
                :enterable="false"
                class="item"
                effect="dark"
                content="删除用户"
                placement="top"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="open(scope.row.id)"
                ></el-button>
              </el-tooltip>

              <el-tooltip
                :enterable="false"
                class="item"
                effect="dark"
                content="分配权限"
                placement="top"
              >
                <el-button
                  type="warning"
                  icon="el-icon-share"
                  size="mini"
                  @click="addrole(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <div class="block">
          <span class="demonstration">选择页数</span>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 3, 4]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="UserInfo.total"
          >
          </el-pagination>
        </div>
      </template>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="resetForm('addUserRef')"
    >
      <template>
        <el-form
          ref="addUserRef"
          :model="addUser"
          label-width="80px"
          :rules="addUserRule"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUser.username"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="addUser.password"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUser.mobile"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUser.email"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserForm('addUserRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="修改用户"
      :visible.sync="dialogVisibleEdit"
      width="50%"
      @close="resetForm('editUserRef')"
    >
      <el-form
        ref="editUserRef"
        :model="editForm"
        label-width="80px"
        :rules="addUserRule"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="showEditForm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配权限" :visible.sync="Visible" width="50%">
      <template>
        <p>当前用户名称:{{ Info.username }}</p>
        <p>当前用户角色:{{ Info.role_name }}</p>
        <p>
          选择角色:
          <el-select v-model="rolevalue" placeholder="请选择">
            <el-option
              v-for="item in RoleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="Visible = false">取 消</el-button>
        <el-button type="primary" @click="editUserRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkUsername = (rule, value, callback) => {
      var length = value.length;
      if (length <= 3 || length >= 11) {
        callback(new Error("请输入3到11个数字或字母"));
      } else {
        callback();
      }
    };

    var checkPassword = (rule, value, callback) => {
      var length = value.length;
      if (length <= 3 || length >= 11) {
        callback(new Error("请输入3到11个数字或字母"));
      } else {
        callback();
      }
    };

    var checkMobile = (rule, value, callback) => {
      var length = value.length;
      if (length <= 3 || length >= 15) {
        callback(new Error("请输入3到11个数字或字母"));
      } else {
        callback();
      }
    };

    var checkEmail = (rule, value, callback) => {
      var length = value.length;
      var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入3到11个数字或字母"));
      }
    };
    return {
      Visible: false,
      rolevalue: "",
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 3,
      },
      Info: {
        id: "",
        username: "",
        role_name: "",
      },

      UserInfo: {
        total: 0,
      },
      UserList: [],
      RoleList: [],
      dialogVisible: false,
      dialogVisibleEdit: false,
      addUser: {
        username: "",
        password: "",
        mobile: "",
        email: "",
      },
      editForm: {},
      addUserRule: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator: checkUsername, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: checkPassword, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUser();
  },
  methods: {
    //获取用户列表
    async getUser() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });

      if (res.meta.status != 200) {
        this.$message.error("用户列表获取失败");
      } else {
        this.UserInfo.total = res.data.total;
        this.UserList = res.data.users;
        console.log(res);
      }
      //   console.log(res);
    },
    //状态按钮变化
    async switchStatus(info) {
      const { data: res } = await this.$http.put(
        "users/" + info.id + "/state/" + info.mg_state
      );
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      } else {
        this.$message.success(res.meta.msg);
      }
      console.log(res);
    },
    //处理页数变化
    handleSizeChange(newpage) {
      console.log(newpage);
      this.queryInfo.pagesize = newpage;
      this.getUser();
    },
    //当前页数变化
    handleCurrentChange(newpage) {
      console.log(newpage);
      this.queryInfo.pagenum = newpage;
      this.getUser();
    },
    //点击搜索用户
    ClearSearch() {
      this.queryInfo.query = "";
      this.getUser();
    },
    //关闭提示框，重置表单
    resetForm(data) {
      this.$refs[data].resetFields();
    },
    //表单预验证
    formValidate(data) {
      this.$refs[data].validate((valid) => {
        if (!valid) {
          this.$message.error("表单验证不通过，请重新输入");
          return false;
        }
        return true;
      });
    },
    //添加用户
    addUserForm(data) {
      this.$refs[data].validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post("users", this.addUser);
          if (res.meta.status !== 201) {
            return this.$message.error("添加用户失败");
          } else {
            this.getUser();
            this.$message.success("添加用户成功");
          }
        } else {
          this.$message.error("用户校验失败");
        }

        this.dialogVisible = false;
      });
    },

    //点击修改按钮
    async clickEditUser(id) {
      this.dialogVisibleEdit = true;
      const { data: res } = await this.$http.get("users/" + id);

      this.editForm = res.data;
      console.log(res);
    },
    //修改用户信息表单
    showEditForm() {
      this.$refs.editUserRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            "users/" + this.editForm.id,
            {
              id: this.editForm.id,
              email: this.editForm.email,
              mobile: this.editForm.mobile,
            }
          );

          if (res.meta.status !== 200) {
            this.$message.error("用户修改失败");
          } else {
            this.$message.success("用户修改成功");
            this.getUser();
            this.dialogVisibleEdit = false;
          }
        }
      });
    },
    //点击删除用户
    async open(id) {
      const flag = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(flag);
      if (flag == "confirm") {
        const { data: res } = await this.$http.delete("users/" + id);
        if (res.meta.status !== 200) {
          return this.$message.error("删除用户失败");
        } else {
          this.$message.success("删除用户成功");
          this.getUser();
        }
      } else {
        this.$message.info("您取消了删除用户");
      }
    },

    //点击分配权限
    async addrole(data) {
      this.Info.id = data.id;
      this.Info.username = data.username;
      this.Info.role_name = data.role_name;
      // console.log(this.Info);
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        this.$message.error("获取角色信息失败");
      } else {
        this.RoleList = res.data;
      }
      this.Visible = true;
    },

    //选择角色之后点击确定
    async editUserRole(){
      if(!this.rolevalue){
        return  this.$message.error('请选择新的角色')
      }

      const {data:res} = await this.$http.put('users/'+this.Info.id+'/role',{
        rid:this.rolevalue
      })

      if(res.meta.status !== 200){
        this.$message.error('更新用户角色失败')
      }else{
        this.$message.success('更新用户角色成功')
        this.getUser()
        this.Visible = false;
      }

      
    }
  },
};
</script>

<style scoped>
.el-card {
  margin-top: 20px;
  box-shadow: 0 0 1px rgba(0, 0, 0, 0.2);
}

.el-table {
  margin-top: 20px;
}
</style>
